//
//  WMEraseWatermarkManuallyViewController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/12.
//

import UIKit

class WMEraseWatermarkManuallyViewController: WMBaseViewController {
    
    @IBOutlet weak var sliderView: UISlider!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint!
    @IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
    
    var image: UIImage?
    var popBlock: ((_ originalImage: UIImage, _ maskImage: UIImage)->Void)?
    
    // 用于绘制擦除路径的画布
    private var drawingImageView: UIImageView!
    // 用于记录擦除路径
    private var erasedPaths: [UIBezierPath] = []
    private var currentPath: UIBezierPath?
    private var lastPoint: CGPoint?
    // 橡皮擦宽度
    private var brushWidth: CGFloat = 20.0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        isNavigationBarHidden = true
        setupGestureRecognizers()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 确保绘制视图的frame正确
        drawingImageView.frame = imageView.bounds
    }
    
    
    private func setupUI() {
        
        // 检查 image 是否存在
        guard let image = image else {
            print("image 为 nil")
            return
        }
        // 设置初始图像
        imageView.image = image
        updateImageViewSize()
        // 创建用于绘制的画布
        drawingImageView = UIImageView(frame: imageView.bounds)
        drawingImageView.isUserInteractionEnabled = false
        drawingImageView.backgroundColor = UIColor.clear
        imageView.addSubview(drawingImageView)
        
        // 设置滑块样式
        sliderView.thumbTintColor = UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0)
        sliderView.value = 0.5
        sliderView.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)
        
        // 初始化橡皮擦宽度
        brushWidth = CGFloat(sliderView.value * 30) + 10
    }
    
    private func setupGestureRecognizers() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
        panGesture.maximumNumberOfTouches = 1
        imageView.addGestureRecognizer(panGesture)
    }
    
    @objc private func sliderValueChanged(_ sender: UISlider) {
        // 根据滑块值调整橡皮擦宽度 (10-40范围)
        brushWidth = CGFloat(sender.value * 30) + 10
    }
    
    @IBAction func closeBtnClickAction(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func sureBtnClickAction(_ sender: Any) {
        
        guard let originalImage = image else { return }
            
            // 创建一个与原始图像相同大小的上下文
            UIGraphicsBeginImageContextWithOptions(originalImage.size, false, originalImage.scale)
            
            // 首先绘制黑色背景（代表未擦除区域）
            UIColor.black.setFill()
            UIRectFill(CGRect(origin: .zero, size: originalImage.size))
            
            // 获取当前上下文
            guard let context = UIGraphicsGetCurrentContext() else {
                UIGraphicsEndImageContext()
                return
            }
            
            // 设置白色作为擦除区域
            context.setFillColor(UIColor.white.cgColor)
            context.setStrokeColor(UIColor.white.cgColor)
            context.setLineCap(.round)
            context.setLineJoin(.round)
            
            // 计算缩放比例
            let scaleX = originalImage.size.width / imageView.bounds.width
            let scaleY = originalImage.size.height / imageView.bounds.height
            
            // 应用缩放变换
            context.scaleBy(x: scaleX, y: scaleY)
            
            // 绘制所有擦除路径
            for path in erasedPaths {
                // 使用描边加填充确保完整覆盖
                context.setLineWidth(path.lineWidth)
                context.addPath(path.cgPath)
                context.strokePath()
                
                // 额外填充路径确保没有空隙
                context.addPath(path.cgPath)
                context.fillPath()
            }
            
            // 获取最终蒙版图像
            let maskImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            // 回调并返回
            if let maskImage = maskImage, let popBlock = popBlock {
                popBlock(self.image!, maskImage)
            }
            
            self.navigationController?.popViewController(animated: true)
    }
    
    //撤销
    @IBAction func undoTapGesture(_ sender: Any) {
        if !erasedPaths.isEmpty {
            erasedPaths.removeLast()
            redrawErasures()
        }
    }
    
    //重置
    @IBAction func resetTapGesture(_ sender: Any) {
        erasedPaths.removeAll()
        drawingImageView.image = nil
    }
    
    @objc private func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
        let location = gesture.location(in: imageView)
        
        switch gesture.state {
        case .began:
            startNewPath(at: location)
        case .changed:
            continuePath(to: location)
        case .ended, .cancelled:
            finishPath()
        default:
            break
        }
    }
    
    private func startNewPath(at point: CGPoint) {
        currentPath = UIBezierPath()
        currentPath?.lineWidth = brushWidth
        currentPath?.lineCapStyle = .round
        currentPath?.lineJoinStyle = .round
        currentPath?.move(to: point)
        lastPoint = point
    }
    
    private func continuePath(to point: CGPoint) {
        guard let currentPath = currentPath, let lastPoint = lastPoint else { return }
           
           // 添加线条到路径
           currentPath.addLine(to: point)
           
           // 在画布上绘制当前路径
           UIGraphicsBeginImageContextWithOptions(drawingImageView.bounds.size, false, 0.0)
           
           // 如果有之前的图像，先绘制
           if let existingImage = drawingImageView.image {
               existingImage.draw(in: drawingImageView.bounds)
           }
           
           // 设置绘制属性 - 使用白色
           UIColor.white.setStroke()
           
           // 绘制当前路径
           currentPath.stroke()
           
           // 更新画布图像
           drawingImageView.image = UIGraphicsGetImageFromCurrentImageContext()
           UIGraphicsEndImageContext()
           
           self.lastPoint = point
    }
    
    private func finishPath() {
        guard let currentPath = currentPath else { return }
        
        // 保存完成的路径
        erasedPaths.append(currentPath)
        self.currentPath = nil
        self.lastPoint = nil
    }
    
    private func redrawErasures() {
        UIGraphicsBeginImageContextWithOptions(drawingImageView.bounds.size, false, 0.0)
          
          // 清空画布
          UIColor.clear.setFill()
          UIRectFill(drawingImageView.bounds)
          
          // 重新绘制所有保存的路径
          UIColor.white.setStroke()
          
          for path in erasedPaths {
              path.stroke()
          }
          
          drawingImageView.image = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()
    }
    
    // 更新图片视图尺寸
    func updateImageViewSize() {
        guard let image = image else { return }
        
        let targetSize = setImageScale(image: image)
        imageViewWidthConstraint.constant = targetSize.width
        imageViewHeightConstraint.constant = targetSize.height
        
        if imageViewWidthConstraint == nil || imageViewHeightConstraint == nil {
                print("约束未正确初始化")
                return
            }
    }
    
    //MARk: 获取图片宽高比
    func setImageScale(image: UIImage)  -> CGSize {
        
        //控件最大尺寸
        let maxWidth = kScreenWidth - 30
        let maxHeight = kScreenHeight - 200
        
        // 获取图片尺寸（以点为单位的尺寸，考虑屏幕缩放）
        let imageSize = image.size
        let imageAspectRatio = imageSize.width / imageSize.height
        let maxAspectRatio = maxWidth / maxHeight
        
        // 根据宽高比决定拉伸方式
        if imageAspectRatio > maxAspectRatio {
            // 宽图：宽度优先
            let targetWidth = min(imageSize.width, maxWidth)
            let targetHeight = targetWidth / imageAspectRatio
            return CGSize(width: targetWidth, height: targetHeight)
        } else {
            // 高图或方图：高度优先
            let targetHeight = min(imageSize.height, maxHeight)
            let targetWidth = targetHeight * imageAspectRatio
            return CGSize(width: targetWidth, height: targetHeight)
        }
        
        
    }
    
}
